package com.aries.ui.view.radius;



import com.aries.ui.view.radius.delegate.RadiusSwitchDelegate;
import ohos.agp.components.AbsButton;
import ohos.agp.components.AttrSet;
import ohos.agp.components.Component;
import ohos.agp.components.Switch;
import ohos.app.Context;

/**
 * @Author: AriesHoo on 2018/7/19 10:06
 * @E-Mail: AriesHoo@126.com
 * Function: switch自定义--api 16以上
 * Description:
 */

public class RadiusSwitch extends Switch implements Component.EstimateSizeListener , AbsButton.CheckedStateChangedListener {
    private RadiusSwitchDelegate delegate;

    public RadiusSwitch(Context context) {
        this(context, null);
    }

    public RadiusSwitch(Context context, AttrSet attrs) {
        super(context, attrs);
        delegate = new RadiusSwitchDelegate(this, context, attrs);
        setEstimateSizeListener(this::onEstimateSize);
        setCheckedStateChangedListener(this::onCheckedChanged);
    }

    /**
     * 获取代理类用于Java代码控制shape属性
     *
     * @return RadiusSwitchDelegate
     */
    public RadiusSwitchDelegate getDelegate() {
        return delegate;
    }

/*
    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (delegate != null) {

            delegate.init();
        }
    }*/

    @Override
    public void setSelected(boolean selected) {
        super.setSelected(selected);
        if (delegate != null) {
            delegate.setSelected(selected);
        }
    }

    @Override
    public boolean onEstimateSize(int i, int i1) {
        if (delegate == null) {
            return false;
        }
        setEstimatedSize(EstimateSpec.getSize(i), EstimateSpec.getSize(i1));
        if (delegate.getWidthHeightEqualEnable() && getEstimatedWidth() > 0 && getEstimatedHeight() > 0) {
            int max = Math.max(getEstimatedWidth(), getEstimatedHeight());
            int measureSpec = EstimateSpec.getSizeWithMode(max, EstimateSpec.PRECISE);
            super.estimateSize(measureSpec, measureSpec);
        }
        if (delegate.getRadiusHalfHeightEnable()) {
            delegate.setRadius((float) (getEstimatedHeight() / (double)2));
        }
        delegate.init();
        return true;
    }

    @Override
    public void onCheckedChanged(AbsButton absButton, boolean b) {
        setChecked(b);
    }
}
